//
//  MDHWKWebViewManager.swift
//  MDHPT
//
//  Created by 高得华 on 2019/5/28.
//  Copyright © 2019年 高得华. All rights reserved.
//

import UIKit

///协议地址
private let urlType = "chengzi://webview?"

///H5管理器的对象
public let kMMWWebVCM = MDHWKWebViewManager.share
///通知
public let kMDHWKWebViewManagerNotification = "kMDHWKWebViewManagerNotification"

/// - ===== H5管理器 ===== -
open class MDHWKWebViewManager: NSObject {
    
    ///下一步的操作
    public var blockPushNextVc: ((_ model: MDHWKWebViewModel)->())?
    
    ///单例
    @objc public static let share = MDHWKWebViewManager.shared
    //在方法内定义静态变量
    @objc public static var shared: MDHWKWebViewManager {
        struct Static {
            static let instance: MDHWKWebViewManager = MDHWKWebViewManager()
        }
        return Static.instance
    }
    private override init() {
        super.init()
    }
    
    ///是否是喵喵玩协议
    @objc open func isMiaomiao(url: String) -> Bool {
        #if DEBUG
            print(url)
        #endif
        return url.hasPrefix(urlType)
    }
    
    ///是否需要进行跳转
    @objc open func push(url: String) -> Bool {
        if url.count <= 0 {
            return false
        }
        var isOk = self.isMiaomiao(url: url)
        if isOk {
            let urlRange = url as NSString
            let urls = (urlRange.replacingOccurrences(of: urlType, with: "") as NSString).replacingPercentEscapes(using: String.Encoding.utf8.rawValue) ?? ""
            if urls.count > 0 {
                let object = (urls as NSString).mj_JSONObject()
                if object != nil && ((object is NSDictionary) || (object is NSArray)) {
                    let model = MDHWKWebViewModel.mj_object(withKeyValues: object) ?? MDHWKWebViewModel()
                    if model.activity.count > 0 {
                        self.pushVc(model: model)
                    }else{
                        isOk = false
                    }
                }else{
                    isOk = false
                }
            }else{
                isOk = false
            }
        }
        return !isOk
    }
    
    
    ///进行页面的跳转 及其他的操作
    @objc open func pushVc(model: MDHWKWebViewModel) -> () {
        if blockPushNextVc != nil {
            blockPushNextVc!(model)
        }
        //NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: kMDHWKWebViewManagerNotification), object: model)
        NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: kMDHWKWebViewManagerNotification), object: self, userInfo: ["data" : model])
        print("asdasdsdsadsaddasd------->\(model.activity)")
        ///进行跳转 当前的管理者 顶部视图 或者 nav
        switch model.activity {
        case "diamondRecharge":
            break
        default:
            break
        }
    }
}


/// - ==== JS 与webView的交互 ==== -
open class MDHWKWebViewModel: NSObject {
    ///页面类型
    @objc public var activity: String = ""
    
    /// - ===== js交互 下载图片 ==== -
    @objc public var pic_url: String = ""
}
